#!/bin/bash

CONTAINER_NAME="dddmr_ws"
IMAGE_NAME="dddmr:x64"
HOST_DIR="/home/jingzedong/dddmr_docker"
CONTAINER_DIR="/home/dddmr_ws"

xhost +local:docker

if [ "$(docker ps -a -q -f name=^/${CONTAINER_NAME}$)" ]; then
    STATUS=$(docker inspect -f '{{.State.Running}}' $CONTAINER_NAME)

    if [ "$STATUS" == "true" ]; then
        echo "容器 $CONTAINER_NAME 已运行，直接进入挂载目录..."
        docker exec -it \
            -e DISPLAY=$DISPLAY \
            -e QT_X11_NO_MITSHM=1 \
            $CONTAINER_NAME bash -c "source /opt/ros/humble/setup.bash; \
                                     source $CONTAINER_DIR/install/setup.bash 2>/dev/null; \
                                     cd $CONTAINER_DIR; exec bash"

    else
        echo "容器 $CONTAINER_NAME 已存在但未运行，启动并进入挂载目录..."
        docker start $CONTAINER_NAME
        docker exec -it \
            -e DISPLAY=$DISPLAY \
            -e QT_X11_NO_MITSHM=1 \
            $CONTAINER_NAME bash -c "source /opt/ros/humble/setup.bash; \
                                     source $CONTAINER_DIR/install/setup.bash 2>/dev/null; \
                                     cd $CONTAINER_DIR; exec bash"
    fi
else
    echo "容器 $CONTAINER_NAME 不存在，创建并启动..."

    docker run -it \
        --name $CONTAINER_NAME \
        -v $HOST_DIR:$CONTAINER_DIR \
        -e DISPLAY=$DISPLAY \
        -e QT_X11_NO_MITSHM=1 \
        -v /tmp/.X11-unix:/tmp/.X11-unix \
        -v /dev/dri:/dev/dri \
        --network host \
        --ipc host \
        --pid host \
        --privileged \
        $IMAGE_NAME \
        bash -c "source /opt/ros/humble/setup.bash; \
                 source $CONTAINER_DIR/install/setup.bash 2>/dev/null; \
                 cd $CONTAINER_DIR; exec bash"
fi
